package com.zzgc.modules.controller;

import com.alibaba.fastjson.JSON;
import com.zzgc.common.entity.*;
import com.zzgc.common.response.Result;
import com.zzgc.common.utils.HttpClientUtil;
import com.zzgc.modules.param.ClassParam;
import com.zzgc.modules.param.CountyParam;
import com.zzgc.modules.param.GradeParam;
import com.zzgc.modules.param.Sort;
import com.zzgc.modules.service.AuthUserService;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.util.ArrayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.util.*;

/**
 *  上传市级服务, 定时任务
 * @Author:
 * @CreateTime: 2023-02-01  10:09
 * @Description:
 * @Version: 1.0
 */
@RestController
@RequestMapping("upload")
public class AutoUpload extends BaseController{
    @Resource
    DataAnalysisController analysisController;

//    @Scheduled(cron = "0 0/30 6-22 * * ?") // 定时任务  每天6点到22点，每半个小时执行一次
//    @Scheduled(cron = "0 * 6-22 * * ?") // 定时任务  每天6点到22点，每分钟执行一次
//    @Scheduled(cron = "0 21 16 * * ?") // 定到时任务  每天6点22点，每分钟执行一次
    @Scheduled(cron = "0 0 12 * * ?") // 定到时任务  每天12点整执行一次
    public void autoRun() {
        // 上传当前学年的所有档案
        uploadStudentAll();
        System.out.println("档案上传执行完毕！=========================");
        // 获取县级所有数据分析数据
        getAllDistrictAnalysis();
        System.out.println("区县数据分析执行完毕！=======================");
        // 获取县级所有以班级为单位的数据分析数据
        getAllSchoolGrade();
        System.out.println("学校数据分析执行完毕！========================");

    }

    /**
     *  获取数据库所有的档案, 上传到市级服务
     * @Author
     * @Description
     * @Date  2023/2/1 10:11
     * @Param
     * @return
     */
    @GetMapping("studentAll")
    //@Scheduled(cron = "0 15 10 * * ?") // 定时任务  每天的10点15分执行
    //@Scheduled(cron = "0 * * * * ?") // 定时任务  每分钟执行一次
//    @Scheduled(cron = "0 * 6-22 * * ?") // 定时任务  每天6点到22点，每分钟执行一次
    public Result uploadStudentAll() {
        System.out.println("======================================定时任务执行=======================================");
        StudentArchives archives = new StudentArchives();
        List<String> list = schoolTableDao.queryAllTableName(super.getDatabaseName(), super.getTableName());
        if (list.size() == 0) {
            return Result.builder().code(200).msg("没有任何学校的档案!").build();
        }
        List<StudentArchives> studentArchives = new ArrayList<>();
        for (String s : list) { // 遍历数据表合并数据
            archives.setTableName(s);
            // 遍历本学年的
//            archives.setSYear(super.getsYear() + "");
            archives.setSYear("2022");
            List<StudentArchives> studentArchives1 = studentArchivesService.queryByPage(archives);
            // 存储数据表名字，方便省级存储
            SysDict sysDict = sysDictService.queryByCode(s.substring(9, 15));
            String substring = "archives_" + sysDict.getSCode() + "_" +archives.getSYear();
            for (StudentArchives archives1 : studentArchives1) {
                archives1.setTableName(substring);
            }
            studentArchives.addAll(studentArchives1);
        }

        if (studentArchives.size() == 0) {
            return Result.builder().code(200).msg("没有最新的数据需要上传!").build();
        }
        String s = HttpClientUtil.doPost(portUrl + "vision/receive/students", studentArchives);
        Result result = JSON.parseObject(s, Result.class);
        System.out.println("parse = " + result);
        List data = (List)result.getData();
        data.forEach(System.out::println);
//        if (result.getCode() == 200) {
//            for (String tableName : list) {
//                studentArchives.get(0).setTableName(tableName);
//                int i = studentArchivesService.maxFlag(tableName);
//                studentArchives.get(0).setSDeleteFlag(i + 1);
//                studentArchivesService.updateDeleteFlags(studentArchives);
//            }
//        }
        //studentArchives.forEach(System.out::println);
        return result;
    }

    /**
     *  上传用户信息, 学校信息, 部门信息 TODO : 制作限制用户登录接口
     * @Author
     * @Description
     * @Date  2023/2/1 10:11
     * @Param
     * @return
     */
    @GetMapping("userSchoolAll")
    public Result uploadUserSchool(){
        AuthUser user = new AuthUser();
        user.setPageable(PageRequest.of(0, Integer.MAX_VALUE));
        Page<AuthUser> authUsers = userService.queryByPageSchoolName(user);
        System.out.println("authUsers = " + authUsers.getContent());
        List<AuthUser> content = new ArrayList<>();
        for (AuthUser authUser : authUsers.getContent()) {
            School school = schoolService.queryById(authUser.getASchoolId());
            AuthDepart authDepart = authDepartService.queryById(authUser.getADepartId());
            authUser.setDepart(authDepart);
            authUser.setSchool(school);
            content.add(authUser);
        }
        for (AuthUser authUser : content) {
            System.out.println("authUser = " + authUser);
        }
        String s = HttpClientUtil.doPost(portUrl + "vision/receive/schools", content);
        Result result = JSON.parseObject(s, Result.class);
        System.out.println("parse = " + result);
        return result;
    }

    /**
     *  获取县级所有数据分析数据
     * @Author
     * @Description
     * @Date  2023/5/18 17:00
     * @Param
     * @return
     */
    @GetMapping("getAllDistrictAnalysis")
    public Result getAllDistrictAnalysis() {
        List<String> list = schoolGradeService.queryByYear(new SchoolGrade());
        ArrayList<CountyParam> list1 = new ArrayList<>();
        for (String s : list) {
            for (int i = 1; i <= 4; i++) {
                Result countyAnalysis = analysisController.AutoGetCountyAnalysis(s, i);
                if (countyAnalysis.getMsg().equals("暂无数据")) {
                    continue;
                }
                CountyParam data = (CountyParam) countyAnalysis.getData();
                String countyName = data.getCountyName();
                data.setCountyName(countyName.substring(0,countyName.indexOf("_") + 1) + s + "_" + i);
                list1.add(data);
            }
        }
        // 发送请求
        HttpClientUtil.doPost(portUrl + "vision/receive/allDistrictAnalysis", list1);
        list1.forEach(System.out::println);
        return Result.builder().build();
    }

    /**
     *  获取县级所有以班级为单位的数据分析数据
     * @Author
     * @Description
     * @Date  2023/5/18 17:00
     * @Param
     * @return
     */
    @GetMapping("getAllSchoolGradeAnalysis")
    public Result getAllSchoolGrade() {
        List<String> tables = schoolTableDao.queryAllTableName(super.getDatabaseName(), super.getTableName());
        List<String> years = schoolGradeService.queryByYear(new SchoolGrade());
        List<GradeParam> list = new ArrayList<>();
        // 遍历学校
        for (String table : tables) {
            // archives_410105_10
            String[] split = table.split("_");
            // 根据学校id查询信息
            School school = schoolService.queryById(Long.valueOf(split[2]));
            for (String year : years) { // 遍历年份
                for (int i = 1; i <= 4; i++) { // 遍历筛查次数
                    List<GradeParam> gradeAnalysis = getGradeAnalysis(year, i, Long.valueOf(split[2]), split[1]);
                    if (gradeAnalysis.size() == 0) {
                        continue;
                    }
                    for (GradeParam analysis : gradeAnalysis) {
                        analysis.setGradeName(split[1] + "_" + year + "_" + i + "_" + school.getSType() + "_" +analysis.getGradeName());
                    }
//                    CountyParam data = (CountyParam) countyAnalysis.getData();
//                    String countyName = data.getCountyName();
//                    data.setCountyName(countyName.substring(0,countyName.indexOf("_") + 1) + s + "_" + i);
                    list.addAll(gradeAnalysis);
                }
            }
        }
        list.forEach(System.out::println);
        // 发送请求
        HttpClientUtil.doPost(portUrl + "vision/receive/allGradeAnalysis", list);
        return Result.builder().build();
    }

    // 获取学校所有年级数据信息
    public List<GradeParam> getGradeAnalysis(String year, Integer number, Long schoolId, String regionId){
        List<GradeParam> list = new ArrayList<>();
        // 查询检测数据
        StudentArchives archives = new StudentArchives();
        archives.setTableName("archives_" + regionId + "_" + schoolId);
        archives.setSSchoolId(schoolId);
        archives.setSYear(year);
        archives.setSNumber(number);
        //archives.setSGradeName(schoolGrade.getSName());
        School school = studentArchivesService.queryAll(archives);
        //System.out.println("school = " + school);
        if (school == null) {
            System.out.println("查询没有该学校筛查记录！" + schoolId + "_"+number);
            return new ArrayList<>();
        }
        for (SchoolGrade grade : school.getSchoolGradeList()) { // 年级
            GradeParam gradeParam = new GradeParam();
            // 根据年级名字查询id
            SchoolGrade schoolGrade = new SchoolGrade();
            schoolGrade.setSSchoolId(schoolId);
            schoolGrade.setSYear(year);
            schoolGrade.setSName(grade.getSName());
            List<SchoolGrade> schoolGrades = schoolGradeService.queryByPage(schoolGrade);
            Student student = new Student();
            if (schoolGrades.size() == 0) {
                System.out.println("查询年级id出错！");
                return new ArrayList<>();
            }
            // 查询年级总人数
            student.setSSchoolId(schoolId);
            student.setSYear(year);
            student.setSGradeId(schoolGrades.get(0).getId());
            long gradeCount = studentService.count(student); // 总人数
            for (SchoolGradeClass schoolGradeClass : grade.getGradeClassList()) { // 班级
                for (StudentArchives studentArchives : schoolGradeClass.getArchivesList()) { // 学生

                    // 统计男女数量
//                    if (studentArchives.getSSex().equals("男")) {
//                        gradeParam.setManCount(gradeParam.getManCount() + 1);
//                    } else {
//                        gradeParam.setWomanCount(gradeParam.getWomanCount() + 1);
//                    }
                    // 统计视力异常, 视力不良人数 - 裸眼视力 < 5.0
                    float r = Float.parseFloat(studentArchives.getSRightEyeVisual() == null ? "9" : studentArchives.getSRightEyeVisual());
                    float l = Float.parseFloat(studentArchives.getSLeftEyeVisual() == null ? "9" : studentArchives.getSLeftEyeVisual());
                    if (r < 5.0 || l < 5.0) {
                        gradeParam.setAbnormalVision(gradeParam.getAbnormalVision() + 1);
//                        if (r < 5.0) { // 左右眼统计
//                            classParam.setAbnormalVisionR(classParam.getAbnormalVisionR() + 1);
//                        } else {
//                            classParam.setAbnormalVisionL(classParam.getAbnormalVisionL() + 1);
//                        }
                        float r1 = Float.parseFloat(studentArchives.getSRightEquivalentMirror() == null ? "9" : studentArchives.getSRightEquivalentMirror());
                        float l1 = Float.parseFloat(studentArchives.getSLeftEquivalentMirror() == null ? "9" : studentArchives.getSLeftEquivalentMirror());
                        // 统计近视人数, -- 裸眼视力 < 5.0 并且等效球镜度数 <= -0.5
                        if (r1 <= -0.50 || l1 <= -0.50) {
                            gradeParam.setMyopia(gradeParam.getMyopia() + 1);
                        }
//                        if (r1 < -6.00 || l1 < -6.00) { // 三预警 三级放前边否则三级的也会算到级二级里
//                            gradeParam.setThreeCount(gradeParam.getThreeCount() + 1);
//                        } else if ((r1 < -0.50 && r1 >= -6.00) || (l1 < -0.50 && l1 >= -6.00)) { // 二级预警
//                            gradeParam.setTwoCount(gradeParam.getTwoCount() + 1);
//                        }
                    } else {
                        gradeParam.setNormalVision(gradeParam.getNormalVision() + 1);
                    }
                }
            }
            // 已经测试的学生人数
            archives.setSGradeName(grade.getSName());
            long archivesCount = studentArchivesService.count(archives);
            gradeParam.setCount((int) gradeCount); // 年级总人数
            gradeParam.setInspect((int) archivesCount); // 年级已测总人数
            gradeParam.setGradeName(school.getSName() + "_" + grade.getSName()); //年级名字
            list.add(gradeParam);
        }
        return list;
    }

}
